/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.jcbp.builder.checkers;

import java.util.ArrayList;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipsejcde.core.CheckerStatus;
import org.eclipsejcde.core.IChecker;
import org.eclipsejcde.core.ICheckerStatus;
import org.eclipsejcde.core.JCDECore;

/**
 * @author Amgad S Youssef
 * 
 */
public class AppletConstructorsChecker implements IChecker {
	@Override
	public ICheckerStatus[] check(IResource resource) throws JavaModelException {
		if (!(resource instanceof IFile)) {
			return new ICheckerStatus[] {};
		}
		if (!resource.getName().endsWith(".java")) {
			return new ICheckerStatus[] {};
		}
		IJavaElement javaElement = JavaCore.create(resource);
		if (!(javaElement instanceof ICompilationUnit)) {
			return new ICheckerStatus[] {};
		}
		ICompilationUnit compilationUnit = (ICompilationUnit) javaElement;
		if (!JCDECore.isJavacardApplet(compilationUnit)) {
			return new ICheckerStatus[] {};
		}
		ArrayList statusList = new ArrayList();
		IType type = compilationUnit.findPrimaryType();
		IMethod[] methods = type.getMethods();
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].isConstructor()) {
				if (Flags.isPublic(methods[i].getFlags())) {
					ICheckerStatus checkerStatus = new CheckerStatus(IMarker.SEVERITY_WARNING, "Using public constructors is not recommended in Java Card applets", methods[i].getNameRange()
							.getOffset(), methods[i].getNameRange().getOffset() + methods[i].getNameRange().getLength());
					statusList.add(checkerStatus);
				}
			}
		}
		ICheckerStatus[] checkStatuses = new ICheckerStatus[statusList.size()];
		statusList.toArray(checkStatuses);
		return checkStatuses;
	}
}
